package com.haidechizi.leetcode;

import java.util.Stack;

public class _150_逆波兰表达式求值 {

    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            if (isOperator(token)) {
                int right = stack.pop();
                int left = stack.pop();
                stack.push(operate(token, left, right));
            } else {
                stack.push(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }

    private int operate(String token, int left, int right) {
        switch (token) {
            case "+":
                return left + right;
            case "-":
                return left - right;
            case "*":
                return left * right;
            case "/":
                return left / right;
            default:
                break;
        }
        return 0;
    }

    public boolean isOperator(String token) {
        if ("+-*/".contains(token)) {
            return true;
        }
        return false;
    }
}
